<?php
// +----------------------------------------------------------------------
// | 后台用户管理
// +----------------------------------------------------------------------
namespace app\common\model;
use think\Model;

class CouponUser extends Model
{
	use \base\model\ModelTrait;
	// 自动完成, 只在新增的时候有效
	protected $insert = [];
	//事件观察
	protected static function init(){
    	self::observe(\app\common\event\CouponUser::class);
    }
	// ----------------
	// ---模型事件---
	//----------------
	//关联店铺信息，一对一关联
	public function shopList(){
        return $this->hasMany('shop','id','shop_id');
    }
	
	/**
     * 验证规则
     */
	protected $rule = [
		'shop_id'=>'require|integer',
		'goods_id'=>'require',
		'name'=>'require',
    	'price' => 'require|float|min:0',
    	'total_num' => 'require|float|min:0',
    	'can_num' => 'require|float|min:0',
    	'use_min_price' => 'require|float|min:0',
    	'start_time' => 'require|date',
    	'stop_time' => 'require|date|gt:start_time',
	];
	
	/**
     * 获取用户优惠券列表
     * @return type
     */
	public function getUserCouponList($uid,$state='',$is_give=-1)
    {
    	$d = date("Y-m-d");
    	$model = new self;
		$model = $model->where('uid',$uid);
		$model = $model->where('num > use_num');
		if( $state == 0 && $state !='' ){
			$model = $model->where('status',0);
			$model = $model->where('stop_time','>=',$d);
		}
		if( $state == 1 ){
			$model = $model->where('status',1);
		}
		if( $state == -1 ){
			$model = $model->where('status','<>',1);
			$model = $model->where('stop_time','<',$d);
		}
		if( $state == -2 ){
			$model = $model->where('status','<>',1);
			$model = $model->where('start_time','>',$d);
			$model = $model->where('stop_time','>',$d);
		}
		if( $is_give !=-1 ){
			$model = $model->where('is_give',$is_give ?: 0 );
		}
		$model = $model->field("
			if( status=1, 1,
				if( stop_time < '$d' , -1
					,if( start_time > '$d' , -2 , 0 )
				) 
			) as state
		");
		$model = $model->field("parent_id,is_del,add_time,is_discount,is_remind",true);
		$model = $model->field("
			if(	goods_id>0,
				concat('满',full_cond_reduce,'元,部分商品可用'),
				concat('满',full_cond_reduce,'元,全部商品可用')
			) use_condition
		");
		$model = $model->order('add_time', 'desc');
		return $model->select();
    }
		
	/**
     * 获取用户优惠券列表
     * @return type
     */
	public function details($id)
    {
    	$d = date("Y-m-d H:i:s");
    	$model = new self;
		$model = $model->with(['shopList']);
		$model = $model->field("if(status=1,1,if(stop_time<'$d',-1,if(start_time>'$d',-2,0)) ) as state");
		$model = $model->field("is_del,add_time,is_discount,is_remind",true);
		$model = $model->field("
			if(	goods_id>0,
				concat('满',full_cond_reduce,'元,部分商品可用'),
				concat('满',full_cond_reduce,'元,全部商品可用')
			) use_condition
		");
		return $model->get($id);
    }	
		
	
	/**
     * 获取用户对订单可用的优惠券
     * @return type
     */
    protected  $beUsableCoupon_is_group = 0;
    //是否分组
    public function setGroup($is=1){ $this->beUsableCoupon_is_group = $is; return $this; }
	public  function beUsableCoupon($uid,$cartInfo,$price,$cid=0){
    	$model = new self;
		$model = $model->where('uid',$uid);
		$model = $model->where('status',0);
		$model = $model->where('type','<>','线下');
		$model = $model->where('full_cond_reduce','<=',$price);
		if($cid) $model = $model->where('id',$cid);
		
		$shop_ids = array_column($cartInfo, 'shop_id');
		$model = $model->where(function ($query) use($shop_ids) {
			$query->whereNull('shop_id');
			$query->whereor('shop_id','');
			foreach ($shop_ids as $key => $value) {
				$query->whereor([['','exp',\Db::raw("find_in_set($value,shop_id)")]]);
			}
		});
					
		$goods_ids = array_column($cartInfo, 'goods_id');	
		$model = $model->where(function ($query) use($goods_ids) {
			$query->whereNull('goods_id');
			$query->whereor('goods_id','');
			$query->whereor('goods_id',0);
			$query->whereor( function($query) use($goods_ids) {
				foreach ($goods_ids as $key => $value) {
					$query->where([['','exp',\Db::raw("find_in_set($value,goods_id)")]]);
				}
			});
		});
		
		$goods_types = [];
		foreach($cartInfo as $key => $value){ $goods_types[]=$value['goods']['goods_type'];}
		$model = $model->where(function ($query) use($goods_types) {
			$query->whereNull('can_proj_type');
			$query->whereor('can_proj_type','');
			$query->whereor('can_proj_type',0);
			foreach ($goods_types as $key => $value) {
				$query->whereor([['','exp',\Db::raw("find_in_set($value,can_proj_type)")]]);
			}
		});
		
		$model = $model->where(function ($query) {
			$d =  date("Y-m-d"); $h =  date("H:i:s"); $dh =  date("Y-m-d H:i:s");
			$query->where(function ($query) use($d,$h,$dh) {
				$query->where('can_day','=',0);
			});
			$query->whereor(function ($query) use($d,$h,$dh) {
				$query = $query->where('can_day','>',0);
				$query = $query->where('start_time','<=',$d);
				$query = $query->where([['','exp',\Db::raw("date_format(now(),'%Y-%m-%d')<= stop_time")]]);
			});
		});
		
		$model = $model->field("status,parent_id,is_del,add_time,is_discount,is_remind",true);
		$model = $model->field("
			if(	goods_id>0,
				concat('满',full_cond_reduce,'元,部分商品可用'),
				concat('满',full_cond_reduce,'元,全部商品可用')
			) use_condition
		");
		$model = $model->order('add_time', 'desc');
		
		if($this->beUsableCoupon_is_group){
			$model = $model->group('parent_id');
		}
		
		return $model->select()->toArray();
    }
	
	/**
     * 使用优惠券
     * @return type
     */
	public static function useCoupon($id)
    {
        return self::where('id',$id)->update([ 'status'=>1, 'use_time'=>date("Y-m-d H:i:s") ]);
    }
    
    /**
     * 领取优惠券
     * @param type $id
     * @return type
     */
	public static function receive($id,$uid)
    {
    	if( !$data = self::details($id) ){
    		throw new \think\Exception('优惠券不存在！');
    	}
    	if($data['state'] != 0 ){
    		throw new \think\Exception('优惠券已过期！');
    	}
    	if( $data->is_give != 1){
    		throw new \think\Exception('不能领取该优惠券！');
    	}
    	if( $data->num - $data->use_num <= 0 ){
    		throw new \think\Exception('该优惠券已被全部领取！');
    	}
    	if( self::where('parent_id',$data->parent_id)->where('oid_uid',$data->uid)->find() ){
    		throw new \think\Exception('不能重复领取！');
    	}
    	$data->use_num	= $data->use_num + 1;
    	$res = true && $data->save();
    	$res = $res && model('Coupon')->where("id",'in',$data->parent_id)->setInc('remain_num',1);
    	$res = $res && model('Coupon')->grant($data->parent_id,$uid);
    	$res = $res && self::where('parent_id',$data->parent_id)->update(['oid_uid'=>$data->uid]);
//  	$stopTime = ($data['can_day'] ?: 1000) - 1;
//  	$data->oid_uid = $data->uid;
//  	$data->uid = $uid;
//  	$data->is_give = 0;
//  	$data->add_time = date("Y-m-d H:i:s");
//  	$data->start_time = date('Y-m-d');
//  	$data->stop_time = date("Y-m-d",strtotime("+$stopTime  day"));
    	return $res;
    }
    
}
